<template>
  <div>
    <!-- 订单财务审核-->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110" @resetChange="resetChange"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTables
        ref="table"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        columnsRef="zjOrderFinancialAudit"
        :pageSize="pageSize"
        :pageSizesArray="pageSizesArray"
        :onRowSelectChange="selectChangeHandle"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary" :click="addHandle.bind(this, 1)" :disabled="isOpen">审核通过</multiuse-button>
          <multiuse-button size="small" type="primary" :click="addHandle.bind(this, 2)" :disabled="isOpen">审核驳回</multiuse-button>
          <multiuse-button size="small" type="primary" :click="addHandle.bind(this, 3)">导 出</multiuse-button>
        </template>
      </FilterTables>
    </Spin>

    <BaseDialog :visible.sync="issearch" :title="'经销商查询'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ownerSeacher @close="dealercloseHandler" />
    </BaseDialog>

    <Drawer :visible.sync="detailVisible" :title="'订单信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="72%">
      <detailModel :rowData="formData" @close="emitcloseHandler" />
    </Drawer>
    <BaseDialog :visible.sync="isreject" :title="'审批驳回'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <reject :list="selectList" @close="rejectClose" />
    </BaseDialog>
  </div>
</template>
<script>
import {
  getList,
  excelList,
  getNotPage,
  getDeptList,
  getOfficeList,
  gettmFiAccountType,
  vehicleConfiguration,
  postconfirmPass,
  gettmVsWarehouse,
  exporturl
} from '@/api/omSale/OrderManagement/OrderFinancialAudit/index.js';
import detailModel from './detailModel';
import ownerSeacher from './ownerSeacher';
import reject from './reject';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils';
import { getAppId } from '@/assets/js/auth'; //获取登录用户
export default {
  name: 'OrderFinancialAudit',
  data() {
    this.BaseTable = null;
    return {
      pageSize: 20,
      pageSizesArray: [10, 20, 30, 40, 100],
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: getList,
      fetchParams: {
        xhrAbort: true
      },
      exportLoading: false,
      formData: {},
      issearch: false,
      detailVisible: false,
      selectList: [],
      isOpen: true,
      isreject: false
    };
  },
  components: {
    ownerSeacher,
    detailModel,
    reject
  },
  mixins: [dictionary],
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    if (getAppId() == 'beijing') {
      this.pageSize = 150;
      this.pageSizesArray = [10, 20, 30, 40, 100, 150];
    }
  },
  created() {
    this.getvehicleList();
    this.getDeptList();
    this.gettmFiAccountType();
    this.gettmVsWarehouse();
  },
  methods: {
    createdFrom() {
      return [
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCodes',
          placeholder: '请选择',
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入'
        },
        {
          type: 'RANGE_DATE',
          label: '提交日期',
          fieldName: 'reportDateBegin|reportDateEnd',
          placeholder: '请选择',
          initialValue: [],
          dateType: 'exactdaterange'
        },
        {
          type: 'SELECT',
          label: '事业部',
          fieldName: 'deptId',
          placeholder: '请选择',
          itemList: [],
          change: p => {
            if (p) {
              this.topFilterList.map(x => {
                if (x.fieldName == 'officeId') {
                  x.itemList = [];
                  x.initialValue = '';
                }
              });
              this.getOfficeList(p);
            } else {
              this.topFilterList.map(x => {
                if (x.fieldName == 'officeId') {
                  x.itemList = [];
                  x.initialValue = '';
                }
              });
            }
          }
        },
        {
          type: 'SELECT',
          label: '办事处',
          fieldName: 'officeId',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'RANGE_DATE',
          label: '审批日期',
          fieldName: 'checkDateBegin|checkDateEnd',
          placeholder: '请选择',
          initialValue: [],
          dateType: 'exactdaterange'
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'orderType',
          placeholder: '请选择',
          itemList: this.createDictList('6006'),
          change: p => {
            if (p) {
              this.topFilterList.find(x => x.fieldName == 'orderDetailType').itemList = [];
              this.topFilterList.find(x => x.fieldName == 'orderDetailType').initialValue = '';
              this.getNotPage(p);
            } else {
              this.topFilterList.find(x => x.fieldName == 'orderDetailType').itemList = [];
              this.topFilterList.find(x => x.fieldName == 'orderDetailType').initialValue = '';
            }
          }
        },
        {
          type: 'SELECT',
          label: '订单类型细分',
          fieldName: 'orderDetailType',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'RANGE_DATE',
          label: '分配日期',
          fieldName: 'matchDateBegin|matchDateEnd',
          placeholder: '请选择',
          initialValue: [],
          dateType: 'exactdaterange'
        },
        {
          type: 'SELECT',
          label: '资金类型',
          fieldName: 'accountType',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'TEXT_AREA',
          label: 'VIN',
          fieldName: 'vins',
          placeholder: '请输入',
          maxlength: '',
          maxRows: 2
        },
        {
          type: 'RANGE_DATE',
          label: '确认日期',
          fieldName: 'confirmDateBegin|confirmDateEnd',
          placeholder: '请选择',
          initialValue: [],
          dateType: 'exactdaterange'
        },
        {
          type: 'SELECT',
          label: '工厂仓库',
          fieldName: 'parentWarehouseId',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'INPUT_CASCADER',
          label: '车型选择',
          fieldName: 'brandProductList',
          placeholder: '请选择',
          options: { titles: ['品牌', '车系', '车型', '配置', '选装', '颜色'] },
          itemList: []
        },
        {
          type: 'SELECT',
          label: '动力形式',
          fieldName: 'powerType',
          placeholder: '请选择',
          itemList: this.createDictList('6008')
        },
        {
          type: 'INPUT',
          label: '销售订单编号',
          fieldName: 'doNo',
          placeholder: '请选择'
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 50,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 2)}>
                  详情
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '事业部',
          dataIndex: 'deptName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '办事处',
          dataIndex: 'officeName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '订货单编号',
          dataIndex: 'orderNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'center',
          width: 200
        },
        {
          title: '销售订单号',
          dataIndex: 'doNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'center',
          width: 200
        },
        {
          title: '订单类型',
          dataIndex: 'orderType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('6006'),
          render: p => {
            return <span>{this.createDictText(p.row.orderType, '6006')}</span>;
          }
        },
        {
          title: '订单细分类型',
          dataIndex: 'orderDetailTypeName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '订单状态',
          dataIndex: 'orderStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('6002'),
          render: p => {
            return <span>{this.createDictText(p.row.orderStatus, '6002')}</span>;
          }
        },
        {
          title: '资金类型',
          dataIndex: 'accountTypeName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '订单年月',
          dataIndex: 'orderYearMonth',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '收车地址',
          dataIndex: 'address',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '要求交付日期',
          dataIndex: 'requiredDeliveryDate',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'vin',
          dataIndex: 'vin',
          align: 'center',
          width: 180,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '产品代码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '产品名称',
          dataIndex: 'productName',
          align: 'center',
          width: 400,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配置',
          dataIndex: 'packageName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '选装',
          dataIndex: 'optionName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '内饰',
          dataIndex: 'trimName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '工厂仓库',
          dataIndex: 'parentWarehouse',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '临时库',
          dataIndex: 'childWarehouse',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '分配数量',
          dataIndex: 'matchCount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '市场指导价',
          dataIndex: 'singleAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '国补金额',
          dataIndex: 'subsidyAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '折扣金额',
          dataIndex: 'discountAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '折扣率(%)',
          dataIndex: 'discount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '折后单价',
          dataIndex: 'afterDiscountAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '是否使用返利',
          dataIndex: 'isRebate',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: p => {
            return <span>{this.createDictText(p.row.isRebate, '1004')}</span>;
          }
        },
        {
          title: '返利使用金额',
          dataIndex: 'rebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '单车返利金额',
          dataIndex: 'singleRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '建店返利金额',
          dataIndex: 'buildRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '开票价格',
          dataIndex: 'kpjg',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: p => {
            //开票价格为市场指导价-补贴-折扣-返利
            return (
              <span>
                {Number(p.row.singleAmount) -
                  (p.row.subsidyAmount ? Number(p.row.subsidyAmount) : 0) -
                  (p.row.discountAmount ? Number(p.row.discountAmount) : 0) -
                  (p.row.rebateAmount ? Number(p.row.rebateAmount) : 0)}
              </span>
            );
          }
        },
        {
          title: '账户可用余额',
          dataIndex: 'availableAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '运输方式',
          dataIndex: 'transportType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('6004'),
          render: p => {
            return <span>{this.createDictText(p.row.transportType, '6004')}</span>;
          }
        },
        {
          title: '提报时间',
          dataIndex: 'reportDate',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '审核时间',
          dataIndex: 'checkDate',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '分配时间',
          dataIndex: 'matchDate',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '确认日期',
          dataIndex: 'confirmDate',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '备注',
          dataIndex: 'remark',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
         {
          title: '审批识别码',
          dataIndex: 'majorOaNumber',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    // 获取车型车系
    async getvehicleList() {
      let res = await vehicleConfiguration(0, { isUnlimited: 10041001 });
      this.topFilterList.find(item => item.fieldName === 'brandProductList').itemList = res.data;
    },
    async getDeptList() {
      let res = await getDeptList({ orgType: 15061005 });
      let arr = res.data.map(x => ({ text: x.orgName, value: x.orgId }));
      this.topFilterList.find(x => x.fieldName == 'deptId').itemList = arr;
    },
    async getOfficeList(orgid) {
      let res = await getOfficeList({ orgType: 15061007, parentOrgId: orgid });
      let arr = res.data.map(x => ({ text: x.orgName, value: x.orgId }));
      this.topFilterList.find(x => x.fieldName == 'officeId').itemList = arr;
      this.topFilterList.find(x => x.fieldName == 'officeId').initialValue = '';
    },
    async getNotPage(orderType) {
      let list = await getNotPage({ orderType: orderType });
      this.topFilterList.map(x => {
        if (x.fieldName == 'orderDetailType') {
          x.itemList = list.data.map(x => ({ text: x.subName, value: x.subId }));
        }
      });
    },
    async gettmFiAccountType() {
      let res = (await gettmFiAccountType({ fundsType: 0 })).data.map(x => ({ text: x.accountTypeName, value: x.id }));
      // this.columns.find(x=>x.dataIndex=='accountType').editItems=res;
      // this.columns.find(x=>x.dataIndex=='accountType').filterItems=res;
      this.topFilterList.find(x => x.fieldName == 'accountType').itemList = res;
    },
    async gettmVsWarehouse() {
      let res = (await gettmVsWarehouse({})).data.map(x => ({ text: x.warehouseName, value: x.id }));
      this.topFilterList.find(x => x.fieldName == 'parentWarehouseId').itemList = res;
    },
    selectChangeHandle(row) {
      if (row.length > 0) {
        this.selectList = row || [];
        this.isOpen = false;
      } else {
        this.selectList = [];
        this.isOpen = true;
      }
    },
    seacherFun() {
      this.issearch = true;
    },
    async addHandle(type) {
      if (type == 1) {
        await this.$confirm('是否审核通过?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            let arr = [];
            this.selectList.map(x => {
              arr.push(x.id);
            });
            let res = await postconfirmPass(arr);
            if (res.resultCode == 200) {
              this.$notify({
                title: '成功',
                message: '审核通过成功',
                type: 'success'
              });
              this.isOpen = true;
              this.fetchParams = Object.assign({}, this.fetchParams);
            }
          })
          .catch(() => {});
      } else if (type == 2) {
        this.isreject = true;
      } else {
    let json = Object.assign({}, { CODE: 'CODE_0000038' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }


        // this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        //   confirmButtonText: '下载',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // })
        //   .then(() => {
        //     let json = this.fetchParams;
        //     this.exportLoading = true;
        //     excelList(json)
        //       .then(response => {
        //         exportExcelFile(response.data, '财务审核');
        //         this.exportLoading = false;
        //       })
        //       .catch(err => {
        //         console.log(err);
        //       });
        //   })
        //   .catch(() => {
        //     console.log('456');
        //     this.$message({
        //       type: 'info',
        //       message: '已取消'
        //     });
        //   });
      }
    },
    changeHandle(params) {
      this.isOpen = true;
      this.fetchParams.xhrAbort = false;
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    editHandle(data) {
      this.formData = data;
      this.detailVisible = true;
    },
    emitcloseHandler(val) {
      if (val) {
        this.isOpen = true;
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
      this.detailVisible = false;
    },
    rejectClose(val) {
      if (val) {
        this.isOpen = true;
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
      this.isreject = false;
    },
    dealercloseHandler(val, data) {
      if (data) {
        let dealerCodes = [];
        data.map(x => {
          dealerCodes.push(x.dealerCode);
        });
        this.topFilterList.find(x => x.fieldName == 'dealerCodes').initialValue = dealerCodes.toString();
      }
      this.issearch = false;
    },
    resetChange(val) {
      this.topFilterList.map(x => {
        if (x.fieldName == 'officeId') {
          x.itemList = [];
        }
        if (x.fieldName == 'orderDetailType') {
          x.itemList = [];
        }
      });
      this.fetchParams = Object.assign({}, this.fetchParams);
    }
  }
};
</script>
